<template>
  <div class="app-container">
    <!-- 类别 -->

    <el-row :gutter="24">
      <el-col :lg="24" :xs="24">
        <div class="search-bar">
          <!-- 搜索 -->
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="类型名称" prop="name">
              <el-input
                v-noSpace
                v-model="queryParams.name"
                class="!w-[192px]"
                placeholder="请输入类型名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="创建时间" prop="timeScopes">
              <el-date-picker
                v-model="queryParams.timeScopes"
                type="datetimerange"
                placeholder="选择日期"
                value-format="YYYY-MM-DD HH:mm:ss"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                clearable
                @change="handleQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
              <el-button
                type="warning"
                icon="plus"
                @click="handleEdit({}, 'add')"
                v-hasPerm="'sys:productCategory:edit'"
              >
                新增
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-card shadow="never">
          <el-table v-loading="loading" :data="pageData">
            <el-table-column prop="code" label="类型编码" align="center" />
            <el-table-column prop="name" label="类型名称" align="center" />
            <el-table-column prop="warehouseType" label="存储温度" align="center">
              <template #default="scope">
                {{
                  warehouseTypeList.find(
                    (item) => item.codeValue === scope.row.warehouseType?.toString()
                  )?.codeName
                }}
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="描述" align="center" show-overflow-tooltip />

            <el-table-column prop="createTime" label="创建时间" align="center" />
            <el-table-column label="操作" fixed="right" width="250" align="center">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="handleEdit(scope.row, 'edit')"
                  v-hasPerm="'sys:productCategory:edit'"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  link
                  @click="handleDel(scope.row)"
                  v-hasPerm="'sys:productCategory:del'"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增/修改弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      class="df"
      @close="handleCloseDialog"
    >
      <el-form
        ref="dialogFormRef"
        :model="dialogParams"
        :inline="true"
        label-width="150px"
        :rules="rules"
      >
        <el-form-item label="类别名称" prop="name">
          <el-input
            v-noSpace
            v-model="dialogParams.name"
            placeholder="请输入类别名称"
            clearable
            style="width: 350px"
            maxlength="100"
          />
        </el-form-item>
        <el-form-item label="存储温度" prop="warehouseType">
          <el-select
            v-model="dialogParams.warehouseType"
            placeholder="请输入存储温度"
            clearable
            style="width: 350px"
          >
            <el-option
              v-for="item in warehouseTypeList"
              :key="item.codeValue"
              :label="item.codeName"
              :value="Number(item.codeValue)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input
            v-noSpace
            v-model="dialogParams.remark"
            placeholder="请输入描述"
            clearable
            type="textarea"
            :rows="4"
            style="width: 350px"
            maxlength="500"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer df">
          <el-button v-debounce="submitDialog" type="primary">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import productCategoryAPI, {
  productCategoryPageQuery,
  productCategoryPageVO,
} from "@/api/productCategory/productCategory";
import configApi, { ConfigType, ConfigData } from "@/api/config/config";
import { FormItemRule } from "element-plus/es";

defineOptions({
  name: "User",
  inheritAttrs: false,
});

const warehouseTypeList = ref<ConfigData[]>([]);

const queryFormRef = ref(ElForm);

const queryParams = reactive<productCategoryPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const pageData = ref<productCategoryPageVO[]>();
const total = ref(0);
const listTotal = ref(0);
const loading = ref(false);

// 新增/修改弹窗
const dialog = reactive({
  visible: false,
  title: "",
  type: "",
});
const dialogFormRef = ref(ElForm);

const dialogParams = reactive<{ name: string; remark: string; warehouseType: number }>({
  name: "",
  remark: "",
  warehouseType: NaN,
});

const options = [
  {
    value: "Option1",
    label: "Option1",
  },
  {
    value: "Option2",
    label: "Option2",
  },
  {
    value: "Option3",
    label: "Option3",
  },
  {
    value: "Option4",
    label: "Option4",
  },
  {
    value: "Option5",
    label: "Option5",
  },
];

const rules = reactive<Record<string, FormItemRule[]>>({
  name: [{ required: true, message: "工序名称是必填项", trigger: "blur" }],
  // remark: [{ required: true, message: "工序描述是必填项", trigger: "blur" }],

  warehouseType: [{ required: true, message: "存储温度是必填项", trigger: "blur" }],
});
//产品列表 potato carrot beef
const productList = ref<
  {
    codeName: string;
    codeValue: string;
  }[]
>([]);
const warehouseType = () => {
  configApi.getConfigListByType(ConfigType.WAREHOUSE_TYPE).then((res) => {
    warehouseTypeList.value = res;
  });
};

// 查询
function handleQuery() {
  // loading.value = true;
  console.log("queryParams", queryParams);
  productCategoryAPI
    .getPage(queryParams)
    .then((data) => {
      pageData.value = [...(data?.list as any)];
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  // queryParams.deptId = undefined;
  // queryParams.createTime = undefined;
  handleQuery();
}

onMounted(() => {
  handleQuery();
  warehouseType();
  // handleTotal();
});

function handleEdit(row: any, type: any) {
  dialog.type = type;
  if (type == "edit") {
    dialog.title = "编辑";
    Object.assign(dialogParams, { ...row });
  } else {
    dialog.title = "新增";
    clearDialogFormData();
  }
  dialog.visible = true;
}

function handleDel(row: any) {
  ElMessageBox.confirm("确定要删除该数据吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      productCategoryAPI
        .delDialog({ id: row.id })
        .then((data) => {
          ElMessage.success("操作成功");
          handleQuery();
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      // 取消删除
    });
}

function handleCloseDialog() {
  dialog.visible = false;
  clearDialogFormData();
}

//重置弹窗
function clearDialogFormData() {
  let data = {
    name: "",
    remark: "",
    warehouseType: "",

    id: "",
  };
  Object.assign(dialogParams, { ...data });
}

// 提交弹窗
function submitDialog() {
  dialogFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    let paramsData = <any>{};
    if (dialog.title == "新增") {
      paramsData = {
        name: dialogParams.name,
        remark: dialogParams.remark,
        warehouseType: dialogParams.warehouseType,
      };
    } else {
      paramsData = { ...dialogParams };
    }
    productCategoryAPI
      .submitDialog(paramsData)
      .then((data) => {
        ElMessage.success("操作成功");
        dialog.visible = false;
        handleQuery();
        clearDialogFormData();
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
      })
      .finally(() => {
        loading.value = false;
      });
  });
}
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;
</style>
